import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "@/views/Login.vue"
import Home from "@/views/Home.vue"
import ElementUI from 'element-ui'
import Register from '@/views/Register'
import Product from '@/components/Product.vue'
import Order from '@/views/Order.vue'
import Sift from '@/components/Sift.vue'
import My from '@/views/My.vue'
import Myorder from'@/views/Myorder.vue'
import New from '@/views/New.vue'


Vue.use(ElementUI)
Vue.use(VueRouter)



const routes = [
  {
    path:'/new',
    name:'new',
    component:New,
  },
  {
    path:'/my',
    name:'my',
    component:My,
    meta: {
      isRequired: true
    }
  },
  {
    path:'/myorder',
    name:'myorder',
    component:Myorder,
    meta: {
      isRequired: true
    }
  },
  {
    path:'/product',
    name:'product',
    component:Product,
    meta: {
      isRequired: true
    }
  },
  {
    path: '/order',
    name: 'order',
    component: Order,
    meta: {
      isRequired: true
    }
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      isRequired: true
    }
  },

  {
    path:'/sift',
    name:'sift',
    component:Sift,
    meta: {
      isRequired: true
    }
  },
 
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    },
    meta: {
      isRequired: true
    }
  },
  {
    path: '/register',
    name: 'register',
    component: Register,
    meta: {
      isRequired: false
    }
  },

  {
    path: '/',
    name: 'login',
    component: Login,
    meta: {
      isRequired: false
    }
  }
  
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  // 1.如果访问的是登录页面（无需权限），直接放行
  if (to.path === '/' || to.path === '/register') return next()
  // 2.如果访问的是有登录权限的页面，先要获取token
  const tokenStr = JSON.parse(localStorage.getItem('user'))
  // 2.1如果token为空，强制跳转到登录页面；否则，直接放行
  if (!tokenStr) {
    alert("请登录")
    return next({
      path:('/')
    })
  }
  next()
})





export default router
